﻿using System.Web;
using umbraco.BusinessLogic;
using umbraco.IO;
using System.IO;
using System.Web.Hosting;
using ClientDependency.Core.Config;

namespace TheOutfield.UmbExt.AutoExpireClientDependency
{
    public class AppBase : ApplicationBase
    {
        public AppBase()
        {
            // CSS
            var cssPath = HttpContext.Current.Server.MapPath(SystemDirectories.Css);

            HttpContext.Current.Application.Add("cssWatcher", new FileSystemWatcher(cssPath));
            var cssFsw = (FileSystemWatcher)HttpContext.Current.Application["cssWatcher"];
            cssFsw.EnableRaisingEvents = true;
            cssFsw.IncludeSubdirectories = true;

            cssFsw.Changed += new FileSystemEventHandler(expireClientDependency);
            cssFsw.Created += new FileSystemEventHandler(expireClientDependency);
            cssFsw.Deleted += new FileSystemEventHandler(expireClientDependency);

            // JS
            var jsPath = HttpContext.Current.Server.MapPath(SystemDirectories.Scripts);

            HttpContext.Current.Application.Add("jsWatcher", new FileSystemWatcher(jsPath));
            var jsFsw = (FileSystemWatcher)HttpContext.Current.Application["jsWatcher"];
            jsFsw.EnableRaisingEvents = true;
            jsFsw.IncludeSubdirectories = true;

            jsFsw.Changed += new FileSystemEventHandler(expireClientDependency);
            jsFsw.Created += new FileSystemEventHandler(expireClientDependency);
            jsFsw.Deleted += new FileSystemEventHandler(expireClientDependency);
        }

        protected void expireClientDependency(object sender, FileSystemEventArgs e)
        {
            ClientDependencySettings.Instance.Version += 1;

            var cdPath = HostingEnvironment.MapPath(SystemDirectories.Data + "/TEMP/ClientDependency");

            if (cdPath != null && Directory.Exists(cdPath))
            {
                string[] files = Directory.GetFiles(cdPath);
                foreach (string file in files)
                {
                    File.SetAttributes(file, FileAttributes.Normal);
                    File.Delete(file);
                }
                //Directory.Delete(cdPath, true);
            }
        }
    }
}